import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { appChildRoutes } from './routes'
import pinia from '../stores'
import { useUserStore } from '../stores/user'

const MainLayout = () => import('../layouts/MainLayout.vue')
const LoginView = () => import('../views/auth/LoginView.vue')
const ForbiddenView = () => import('../views/error/ForbiddenView.vue')
const WelcomeView = () => import('../views/WelcomeView.vue')

const resolveRoutes = (): RouteRecordRaw[] => {
  const routes: RouteRecordRaw[] = [
    {
      path: '/login',
      name: 'Login',
      component: LoginView,
      meta: { public: true, title: '登录' }
    },
    {
      path: '/403',
      name: 'Forbidden',
      component: ForbiddenView,
      meta: { public: true, title: '无权限' }
    },
    {
      path: '/welcome',
      name: 'Welcome',
      component: WelcomeView,
      meta: { public: true, title: '欢迎' }
    },
    {
      path: '/',
      component: MainLayout,
      meta: { requiresAuth: true },
      children: [
        { path: '', redirect: '/dashboard', meta: { public: true } },
        ...appChildRoutes as RouteRecordRaw[]
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/dashboard'
    }
  ]
  
  return routes
}

const router = createRouter({
  history: createWebHistory(),
  routes: resolveRoutes()
})

router.beforeEach(async (to, _from, next) => {
  const userStore = useUserStore(pinia)
  if (!userStore.initialized) {
    await userStore.initAuth()
  }

  if (to.meta?.public) {
    next()
    return
  }

  if (!userStore.isAuthenticated) {
    next({ path: '/login', query: { redirect: to.fullPath } })
    return
  }

  const allowRoles = (to.meta?.roles as string[]) || []
  if (allowRoles.length && !userStore.hasSomeRole(allowRoles)) {
    // 如果没有权限访问目标页面，检查是否有可访问的页面
    const accessibleRoutes = resolveRoutes()
      .filter(route => {
        const routeRoles = (route.meta?.roles as string[]) || []
        return !routeRoles.length || userStore.hasSomeRole(routeRoles)
      })
      .flatMap(route => [route, ...(route.children || [])])
      .filter(route => route.path && route.path !== '/login' && route.path !== '/403')
    
    if (accessibleRoutes.length > 0 && (accessibleRoutes[0] as RouteRecordRaw).path) {
      // 重定向到第一个可访问的页面
      next((accessibleRoutes[0] as RouteRecordRaw).path!)
    } else {
      // 如果没有可访问的页面，显示欢迎页面
      next('/welcome')
    }
    return
  }

  next()
})

router.afterEach((to) => {
  if (to.meta?.title) {
    document.title = `${to.meta.title} - 神话学院管理系统`
  }
})

export default router